<template>

	<uni-load-more :status="isLoadingStatus" v-if="isLoading" />
	<view v-else class="search-page">
		<!-- 搜索框区域 -->
		<view class="search-header">
			<uni-easyinput prefixIcon="search" placeholder="请输入搜索关键词" v-model="searchKeyword" @clear="handleClear"
				@input="handleInput" @confirm="handleSearch"></uni-easyinput>
		</view>

		<!-- 推荐搜索区域 -->
		<view v-if="showRecommendSearch" class="recommend-search">
			<view @click="handleSearchRecommend(item)" v-for="(item, index) in recommendSearchData" :key="index"
				class="recommend-search-item">
				<uni-icons type="search" size="20"></uni-icons>
				{{ item }}
			</view>
		</view>

		<!-- 搜索结果列表区域 -->
		<view v-if="showSearchResults" class="search-results">
			<navigator :url="`/pages/book/index?bookId=${book.id}`" v-for="(book, index) in searchResults" :key="index"
				class="book-item">
				<!-- 书籍封面 -->
				<image class="book-cover" :src="`${baseURL}${book.image}`" mode="aspectFill" />

				<!-- 书籍信息 -->
				<view class="book-info">
					<!-- 标题和评分 -->
					<view class="book-header">
						<view class="book-title">
							{{ book.name }}
						</view>
						<view class="book-score">
							{{ book.score }}分
						</view>
					</view>

					<!-- 描述信息 -->
					<view class="book-description">
						{{ book.description }}
					</view>

					<!-- 标签 -->
					<view class="book-tag">
						{{ book.tagOne }}
					</view>
				</view>
			</navigator>
		</view>

		<!-- 排行榜区域 -->
		<scroll-view v-if="showRankings" enable-flex class="rankings-container" scroll-y>
			<!-- 搜索历史区域 -->
			<view class="search-history">
				<view class="search-history-header">
					<text class="search-history-title">搜索历史</text>
					<view @click="toggleShowAll = !toggleShowAll">
						<text>{{ toggleShowAll ? "收起 ˄" : "展开 ˅" }}</text>
					</view>
				</view>
				<!-- 历史列表 -->
				<view class="search-history-list">
					<uni-tag v-for="(item, index) in toggleShowAll ? searchHistory : searchHistory.slice(0, 12)"
						:key="index" :text="item.content" :inverted="true" @click="handleSearchHistory(item)" />
				</view>
			</view>

			<!-- 热搜榜单区域 -->
			<view class="hot-search">
				<scroll-view scroll-x class="hot-search-scroll">
					<view class="hot-search-content">
						<view v-for="(list, index) in hotSearchData" :key="index" class="hot-search-item"
							:class="'rank-bg-' + index">
							<!-- 推荐榜单名称 -->
							<view class="hot-search-item-header">
								<text class="hot-search-item-title">
									{{ list.name }}
								</text>
								<uni-icons type="right" size="14" color="#999" />
							</view>
							<!-- 推荐榜单内容 -->
							<view class="hot-search-item-content">
								<view v-for="(item, idx) in list.books" :key="idx" class="hot-book-item"
									@click="handleHotSearch(item)">
									<!-- 排名 -->
									<text class="book-rank">
										{{ idx + 1 }}
									</text>
									<!-- 标题 -->
									<view class="book-name-container">
										<text class="book-name">
											{{ item.name }}
										</text>
										<text class="book-hot">
											{{ item.hot }}
										</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</scroll-view>
	</view>
</template>

<script lang="ts" setup>
	// 导入依赖
	import { commonPageQueryData } from "@/services/global";
	import {
		queryHotSearchListAPI,
		querySearchHistoryAPI,
		pageQueryBookBySearchKeywordAPI,
		queryRecommendSearchNameAPI,
		querySearchBookApi
	} from "@/services/search";

	import { BookItem } from "../../types/book";
	import { PageParams } from "../../types/global";
	import { HotItem, SearchHistoryItem, SearchParams } from "../../types/search";
	import { onShow } from "@dcloudio/uni-app";
	import { ref } from "vue";
	import { baseURL } from '@/utils/config'

	// 状态控制
	const toggleShowAll = ref(false); // 控制搜索历史是否全部显示
	const searchKeyword = ref(""); // 搜索关键词
	const isLoading = ref(true); // 是否正在加载
	const isLoadingStatus = ref('loading'); // 加载状态
	const finish = ref(false); // 是否加载完成

	// 数据存储
	const searchHistory = ref<SearchHistoryItem[]>([]); // 搜索历史数据
	const hotSearchData = ref<HotItem[]>([]); // 热搜榜单数据
	const recommendSearchData = ref<string[]>([]); // 推荐搜索名称数据
	const searchResults = ref<BookItem[]>([]); // 搜索结果数据

	// 视图控制
	const showSearchResults = ref(false); // 是否显示搜索结果
	const showRankings = ref(false); // 是否显示排行榜
	const showRecommendSearch = ref(false); // 是否显示推荐搜索

	// 分页参数
	const pageParams : Required<PageParams> = {
		current: 1,
		size: 8,
	};
	// 查询参数
	const queryParams = ref<SearchParams>({
		bookName: '',
	});

	/**
	 * 清空搜索框内容
	 */
	const handleClear = () => {
		searchKeyword.value = "";
		showRankingsPage();
	};

	/**
	 * 搜索框开始搜索
	 */
	const handleSearch = () => {
		// 获取搜索列表
		pageQuerySearchBookData();
		// 展示搜索列表
		showSearchResultsPage();
	};

	/**
	 * 搜索框内容改变时触发
	 * @param e 输入框内容
	 */
	const handleInput = (e : any) => {
		// 查询推荐搜索名称
		queryRecommendSearchData();
		// 展示推荐搜索名称
		showRecommendSearchPage();
	};

	/**
	 * 点击推荐搜索名称时触发
	 * @param item 推荐搜索名称
	 */
	const handleSearchRecommend = (item : string) => {
		// 将搜索历史放到搜索框中
		searchKeyword.value = item;
		// 查询书籍列表
		querySearchBookData();
		// 展示搜索列表
		showSearchResultsPage();
	};

	/**
	 * 查询搜索书籍数据
	 */
	const querySearchBookData = async () => {
		querySearchBookApi(searchKeyword.value).then(res => {
			searchResults.value = res.data;
		});
	};

	/**
	 * 展示排行榜页面
	 */
	const showRankingsPage = () => {
		showRankings.value = true;
		showSearchResults.value = false;
		showRecommendSearch.value = false;
	};

	/**
	 * 展示搜索结果页面
	 */
	const showSearchResultsPage = () => {
		showRankings.value = false;
		showSearchResults.value = true;
		showRecommendSearch.value = false;
	};

	/**
	 * 展示推荐搜索页面
	 */
	const showRecommendSearchPage = () => {
		showRankings.value = false;
		showSearchResults.value = false;
		showRecommendSearch.value = true;
	};

	/**
	 * 查询推荐搜索名称数据
	 */
	const queryRecommendSearchData = () => {
		if (searchKeyword.value.length > 0) {
			queryRecommendSearchNameAPI(searchKeyword.value).then(res => {
				// 确保赋值类型匹配，提取推荐搜索名称
				recommendSearchData.value = res.data.map((item : any) => item.name || '');
			});
		}
	};

	/**
	 * 点击搜索历史时触发
	 * @param item 搜索历史项
	 */
	const handleSearchHistory = (item : SearchHistoryItem) => {
		// 将搜索历史放到搜索框中
		searchKeyword.value = item.content;
		// 开始搜索
		handleSearch();
	};

	/**
	 * 点击排行榜中的书籍时触发
	 * @param item 书籍项
	 */
	const handleHotSearch = (item : any) => {
		searchKeyword.value = item.name;
		handleSearch();
	};

	/**
	 * 页面显示时调用
	 */
	onShow(() => {
		isLoading.value = true;
		isLoadingStatus.value = 'loading';
		// 初始化搜索历史
		initSearchHistory();
		// 初始化热搜榜单
		initHotSearchLists();
		// 展示排行榜
		showRankingsPage();

		// 延迟加载
		setTimeout(() => {
			isLoading.value = false;
			isLoadingStatus.value = 'more';
		}, 100);
	});

	/**
	 * 初始化搜索历史数据
	 */
	const initSearchHistory = () => {
		querySearchHistoryAPI().then(res => {
			searchHistory.value = res.data;
		});
	};

	/**
	 * 初始化热搜榜单数据
	 */
	const initHotSearchLists = () => {
		queryHotSearchListAPI().then(res => {
			hotSearchData.value = res.data;
		});
	};

	/**
	 * 分页查询书籍列表
	 */
	const pageQuerySearchBookData = async () => {
		queryParams.value.bookName = searchKeyword.value;
		// 查询书籍列表
		await commonPageQueryData(
			pageQueryBookBySearchKeywordAPI,
			searchResults,
			finish,
			isLoading,
			pageParams,
			queryParams,
		);

		// 截取描述和书名
		searchResults.value.forEach((book) => {
			book.description = book.description!.length > 25
				? book.description!.slice(0, 25) + "..."
				: book.description;
			book.name = book.name!.length > 15
				? book.name!.slice(0, 14) + "..."
				: book.name;
		});
	};
</script>

<style lang="scss" scoped>
	// 搜索页面容器
	.search-page {
		display: flex;
		flex-direction: column;
		height: 100vh;

		// 搜索框区域
		.search-header {
			height: 40px;
			display: flex;
			align-items: flex-end;
			justify-content: center;
			position: fixed;
			width: 100%;
			z-index: 1000;
			background-color: #fff;
			padding: 0 16px;
			box-sizing: border-box;
		}

		// 推荐搜索区域
		.recommend-search {
			display: flex;
			flex-direction: column;
			flex: 1;
			margin-top: 16px;

			.recommend-search-item {
				padding: 0 16px;
				margin-bottom: 16px;
			}
		}

		// 搜索结果区域
		.search-results {
			display: flex;
			flex-direction: column;
			flex: 1;
			margin: 0 8px;
			margin-top: 16px;

			.book-item {
				display: flex;
				flex-direction: row;
				justify-content: center;
				margin-top: 40px;

				.book-cover {
					width: 80px;
					height: 100px;
					border-radius: 8px;
					margin-right: 8px;
				}

				.book-info {
					flex: 1;

					.book-header {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.book-title {
							overflow: hidden;
							white-space: nowrap;
							text-overflow: ellipsis;
						}

						.book-score {
							width: 40px;
							font-weight: bold;
							color: #d97706; // amber-600
						}
					}

					.book-description,
					.book-tag {
						margin-top: 8px;
						font-size: 14px;
						color: #9ca3af; // gray-400
					}
				}
			}
		}

		// 排行榜区域
		.rankings-container {
			flex: 1;
			display: flex;
			flex-direction: column;
			margin-top: 40px;
			overflow: hidden;

			// 搜索历史区域
			.search-history {
				margin: 16px 0;
				height: auto;

				.search-history-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0 32px;

					.search-history-title {
						font-weight: bold;
						font-size: 28px;
					}
				}

				.search-history-list {
					display: flex;
					flex-wrap: wrap;
					gap: 20px;
					padding: 20px;
				}
			}

			// 热搜榜单区域
			.hot-search {
				overflow-y: auto;
				flex: 1;

				.hot-search-scroll {
					width: 100%;
					white-space: nowrap;

					.hot-search-content {
						display: inline-flex;

						.hot-search-item {
							padding: 16px;
							margin: 16px;
							border-radius: 8px;
							width: 384px;

							.hot-search-item-header {
								display: flex;
								align-items: center;
								margin-bottom: 20px;

								.hot-search-item-title {
									padding-left: 10px;
									margin-right: 10px;
									font-weight: bold;
								}
							}

							.hot-search-item-content {
								display: flex;
								flex-direction: column;
								gap: 20px;

								.hot-book-item {
									display: flex;
									flex-direction: row;
									align-items: flex-start;
									padding: 10px 0;

									.book-rank {
										width: 16px;
									}

									.book-name-container {
										display: flex;
										flex-direction: column;
										font-size: 12px;

										.book-name,
										.book-hot {
											// 继承父元素字体大小
										}
									}
								}
							}

							// 分别定义五个元素的背景色
							&.rank-bg-0 {
								background: linear-gradient(0deg,
										rgb(186, 182, 254) 0%,
										rgb(148, 253, 148) 35%);
							}

							&.rank-bg-1 {
								background: linear-gradient(0deg,
										rgb(114, 253, 255) 0%,
										rgb(249, 220, 157) 100%);
							}

							&.rank-bg-2 {
								background: linear-gradient(0deg,
										rgba(244, 85, 85) 0%,
										rgba(254, 203, 132) 100%);
							}

							&.rank-bg-3 {
								background: linear-gradient(0deg,
										rgba(244, 85, 85) 0%,
										rgba(254, 203, 132) 100%);
							}

							&.rank-bg-4 {
								background: linear-gradient(0deg,
										rgba(244, 85, 85) 0%,
										rgba(254, 203, 132) 100%);
							}
						}
					}
				}
			}
		}
	}
</style>